package sum.achilles.com.fragment;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import de.greenrobot.event.EventBus;
import sum.achilles.com.Bean.Bean_NoteInfo;
import sum.achilles.com.Bean.Bean_Note_Item_del;
import sum.achilles.com.Bean.EventBus_Notice;
import sum.achilles.com.database.DBHelper;
import sum.achilles.com.database.NoteInfo;
import sum.achilles.com.sum.R;

public class DeleteFragment extends Fragment implements View.OnClickListener {

    private List<NoteInfo> noteInfos = new ArrayList<>();
    ListViewBaseAdapter listViewBaseAdapter;

    // Content View Elements

    private TextView mTv_del_all_data;
    private ListView mLv_today_data;
    private TextView mTv_empty_data;

    // End Of Content View Elements

    private DBHelper dbHelper;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        dbHelper = DBHelper.getInstance(getActivity());
        EventBus.getDefault().register(this);
        View view = inflater.inflate(R.layout.fragment_delete, null);

        bindViews(view);
        listViewBaseAdapter = new ListViewBaseAdapter(getActivity());
        mLv_today_data.setAdapter(listViewBaseAdapter);

        return view;
    }

    private void bindViews(View rootView) {

        mTv_del_all_data = (TextView) rootView.findViewById(R.id.tv_del_all_data);
        mLv_today_data = (ListView) rootView.findViewById(R.id.lv_today_data);
        mTv_empty_data = (TextView) rootView.findViewById(R.id.tv_empty_data);

        mTv_del_all_data.setOnClickListener(this);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_del_all_data: {
                EventBus.getDefault().post(new EventBus_Notice(EventBus_Notice.CLOSE_DRAWLAYOUT));
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity()).setMessage(R.string.string_clear_data_clear);
                alertDialogBuilder.setPositiveButton(getString(R.string.string_confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        EventBus.getDefault().post(new EventBus_Notice(EventBus_Notice.CLEAR_ALL_DATA));
                    }
                });
                alertDialogBuilder.setNegativeButton(getString(R.string.string_cancel), null);

                alertDialogBuilder.create().show();
                break;
            }
        }
    }

    class DelOnClickListener implements View.OnClickListener {

        int position;

        public DelOnClickListener(int position) {
            this.position = position;
        }

        /**
         * Called when a view has been clicked.
         *
         * @param v The view that was clicked.
         */
        @Override
        public void onClick(View v) {

            NoteInfo noteInfo = noteInfos.get(position);
            EventBus.getDefault().post(new Bean_Note_Item_del(noteInfo.getTimes()));

            Log.e("DelFragment", noteInfo.getDate().toString());
            dbHelper.del_noteInfo_byDate(noteInfo.getDate());

            noteInfos.remove(position);
            listViewBaseAdapter.notifyDataSetChanged();
        }
    }

    class ListViewBaseAdapter extends BaseAdapter {

        LayoutInflater layoutInflater;

        public ListViewBaseAdapter(Context context) {
            layoutInflater = LayoutInflater.from(context);
        }

        /**
         * How many items are in the data set represented by this Adapter.
         *
         * @return Count of items.
         */
        @Override
        public int getCount() {
            return noteInfos.size();
        }

        /**
         * Get the data item associated with the specified position in the data set.
         *
         * @param position Position of the item whose data we want within the adapter's
         *                 data set.
         * @return The data at the specified position.
         */
        @Override
        public Object getItem(int position) {
            return noteInfos.get(position);
        }

        /**
         * Get the row id associated with the specified position in the list.
         *
         * @param position The position of the item within the adapter's data set whose row id we want.
         * @return The id of the item at the specified position.
         */
        @Override
        public long getItemId(int position) {
            return 0;
        }

        /**
         * Get a View that displays the data at the specified position in the data set. You can either
         * create a View manually or inflate it from an XML layout file. When the View is inflated, the
         * parent View (GridView, ListView...) will apply default layout parameters unless you use
         * {@link LayoutInflater#inflate(int, ViewGroup, boolean)}
         * to specify a root view and to prevent attachment to the root.
         *
         * @param position    The position of the item within the adapter's data set of the item whose view
         *                    we want.
         * @param convertView The old view to reuse, if possible. Note: You should check that this view
         *                    is non-null and of an appropriate type before using. If it is not possible to convert
         *                    this view to display the correct data, this method can create a new view.
         *                    Heterogeneous lists can specify their number of view types, so that this View is
         *                    always of the right type (see {@link #getViewTypeCount()} and
         *                    {@link #getItemViewType(int)}).
         * @param parent      The parent that this view will eventually be attached to
         * @return A View corresponding to the data at the specified position.
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            NoteInfo noteInfo = (NoteInfo) getItem(getCount() - 1 - position);
            if (convertView == null) {
                convertView = layoutInflater.inflate(R.layout.item_listview, parent, false);
            }

            TextView tv_content = (TextView) convertView.findViewById(R.id.tv_data_time);
            ImageView iv_del = (ImageView) convertView.findViewById(R.id.iv_del);

            iv_del.setOnClickListener(new DelOnClickListener(position));

            tv_content.setText(String.format(getString(R.string.string_del_item), date2String(noteInfo.getDate()), noteInfo.getTimes()));

            return convertView;
        }
    }

    private String date2String(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm:ss");
        return format.format(date);
    }

    public void onEventMainThread(Bean_NoteInfo bean_noteInfo) {
        List<NoteInfo> bean_noteInfos = bean_noteInfo.getInfoList();

        noteInfos.clear();
        noteInfos = bean_noteInfo.getInfoList();

        listViewBaseAdapter.notifyDataSetChanged();

        if (bean_noteInfos.size() != 0) {
            mLv_today_data.setVisibility(View.VISIBLE);
            mTv_empty_data.setVisibility(View.GONE);
        } else {
            mLv_today_data.setVisibility(View.GONE);
            mTv_empty_data.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
